package com.boot.unity.api.config;

import com.boot.unity.api.Interceptor.SignInterceptor;
import com.boot.unity.api.constants.Constants;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {
    private final RedisTemplate redisTemplate;

	@Value("${spring.profiles.active}")
	private String evn;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedMethods("*")
                        .allowedHeaders("*")
                        .allowedHeaders("/rzgjj/**")
                        .allowCredentials(false)
                        .maxAge(18000L);
            }
        };
    }

    @Bean
    public SignInterceptor signInterceptor(RedisTemplate redisTemplate){
        return new SignInterceptor(redisTemplate);
    }

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
    	if (Constants.PROD_EVN.equalsIgnoreCase(evn)){
			registry.addInterceptor(signInterceptor(redisTemplate))
                    .addPathPatterns(Constants.API_URI_PREFIX)
                    .excludePathPatterns(Constants.EXCLUDE_PATH);
		}
	}

	/** 报名人像照片 */
//    @Value("${train.signup.avatar.path}")
	private String signupAvatarPath;

	/** 文件访问 */
	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
	    registry.addResourceHandler("/statics/**")
                .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + signupAvatarPath + File.separator);
    }

}
